<?php

namespace common\observer;


use common\model\TaskRelationTagModel;
use support\SingletonTrait;
use teamones\dbeventObserver\interfaces\SplSubject;
use teamones\dbeventObserver\interfaces\SplObserver;

/**
 * 分配工序任务计划完成时间被观察对象
 */
class TaskEpisodeIdSyncTaskRelationTag implements SplObserver
{
    use SingletonTrait;

    /**
     * @inheritDoc
     * @throws \Exception
     */
    function update(SplSubject $subject): void
    {
        $updateTaskData = $subject->getSplUpdateData();
        if (empty($updateTaskData['episode_id'])) {
            return;
        }
        $taskData = $subject->getSubjectData();
        //同步标签的剧集id
        $taskRelationTag = model(TaskRelationTagModel::class)->where([
            'task_id' => $taskData['id'],
            'link_module_code' => 'episode'
        ])->field("id,link_id")->find();

        if (!empty($taskRelationTag)) {
            model(TaskRelationTagModel::class)->save([
                'id' => $taskRelationTag['id'],
                'link_id' => $updateTaskData['episode_id'],
            ]);
        } else {
            model(TaskRelationTagModel::class)->addItem([
                'task_id' => $taskData['id'],
                'link_id' => $updateTaskData['episode_id'],
                'link_module_code' => 'episode',
                'tenant_id' => $taskData['tenant_id'],
                'project_id' => $taskData['project_id'],
            ]);
        }
    }

}
